package com.filyar.htyd.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.filyar.htyd.entity.Day;
import com.filyar.htyd.entity.DayType;
import com.filyar.htyd.entity.Schedule;
import com.filyar.htyd.entity.vo.DayVo;
import com.filyar.htyd.mapper.DayMapper;
import com.filyar.htyd.mapper.DayTypeMapper;
import com.filyar.htyd.mapper.ScheduleMapper;
import com.filyar.htyd.service.IDayService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author filyar
 * @since 2024-08-29
 * @e-mail root@filyar.com
 */
@Service
public class DayServiceImpl extends ServiceImpl<DayMapper, Day> implements IDayService {

    @Resource
    private DayMapper dayMapper;
    @Resource
    private DayTypeMapper dayTypeMapper;
    @Resource
    private ScheduleMapper scheduleMapper;

    @Override
    public List<DayVo> customList(String date) {
        System.out.println("-------"+date);
        DateTime parse = DateUtil.parse(date, "yyyy-MM");
        List<DayType> dayTypes = dayTypeMapper.selectList(null);
        List<Day> days = dayMapper.selectList(new LambdaQueryWrapper<Day>()
                .between(Day::getDate, DateUtil.beginOfMonth(parse), DateUtil.endOfMonth(parse))
                .orderByDesc(Day::getDate));
        List<DayVo> dayVos = new ArrayList<>();
        for (Day day : days) {
            DayVo dayVo = new DayVo();
            dayVo.setDayTypeId(day.getDayTypeId());
            dayVo.setDate(day.getDate());
            dayVo.setId(day.getId());
            dayVo.setDayTypeName(dayTypes.stream().filter(dayType -> dayType.getId().equals(day.getDayTypeId())).findFirst().get().getName());
            dayVos.add(dayVo);
        }
        return dayVos;
    }

    @Override
    public void updateDay(Day day) {
        List<Schedule> schedules = scheduleMapper.selectList(new LambdaQueryWrapper<Schedule>()
                .eq(Schedule::getShiftDate, day.getDate()));
        if (CollUtil.isNotEmpty(schedules)) {
            for (Schedule schedule : schedules) {
                schedule.setDayTypeId(day.getDayTypeId());
                scheduleMapper.updateById(schedule);
            }
        }
        dayMapper.updateById(day);

    }


}
